package com.example.block_chain.controller.blockChain;

import com.example.block_chain.RabbitMQ.Producer;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.domain.pbft.VoteEnum;
import com.example.block_chain.domain.pbft.VoteInfo;
import com.example.block_chain.domain.pojo.Award;
import com.example.block_chain.service.award.AwardService;
import com.example.block_chain.service.blockChain.BlockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/*
 *@description: 区块相关接口
 *@author: hisen
 *@Time: 2023/11/22  22:08
 */
@RestController
@Slf4j
public class BlockController {
    @Resource
    BlockService blockService;

    @Resource
    AwardService awardService;

    @Resource
    Producer producer;

    @PostMapping("/block")
    public ResponseResult ToBlockChain(@RequestParam Long awardId) throws UnsupportedEncodingException {
        Award award = awardService.getAward(awardId);
        if (!blockService.haveCode(award.getSchoolCode() + ":" + award.getSNo())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.STUDENT_NOT_FOUND);
        }
        if (blockService.haveAward(award.getDigest())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AWARD_EXISTS);
        }
        VoteInfo voteInfo = blockService.createAwardBlock(award);
        voteInfo.setCode(VoteEnum.REQUEST.getCode());
        System.out.println(voteInfo);
        producer.sendMessage(voteInfo);
        return ResponseResult.okResult();
    }
}
